//
//  NetworkTools.m
//  微看
//
//  Created by 吴明磊 on 15/8/19.
//  Copyright © 2015年 wuminglei. All rights reserved.
//

#import "NetworkTools.h"
#import "AFNetworking.h"


typedef enum : NSUInteger {
    RequestTypePost,
    RequestTypeGet
} RequestType;

@implementation NetworkTools

+ (instancetype)sharedNetwork {

    static NetworkTools *instanse;
    if (!instanse) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            
            
            instanse = [[self alloc]initWithBaseURL:[NSURL URLWithString:@"http://readapi.fotoable.com.cn"]];
            
            instanse.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        });
    }
    
    return instanse;
}


- (void)loadInformation:(void (^)(NSDictionary *))infoData Error:(void (^)(NSError *))Error {

    
    NSString *url = @"http://readapi.fotoable.com.cn/v1/groupNews";
    
    NSDictionary *paramter = @{@"cityId" : @(1), @"groupId" : @(2), @"limit" : @(20), @"mixid" : @(0) ,@"option" : @(1), @"skip" : @(0)};
    
    [self urlRequestWithType:RequestTypePost urlStr:url paramters:paramter success:infoData Error:Error];
}



//MARK: 封装AFN方法
- (void)urlRequestWithType:(RequestType)type urlStr:(NSString *)url paramters:(NSDictionary *)paramter success:(void (^)(NSDictionary *))infoData Error:(void (^)(NSError *))Error {

    if (type == RequestTypePost) {
        
        [self requestPostWithUrlStr:url paramters:paramter success:infoData Error:Error];
    }
    else if (type == RequestTypeGet) {
    
        [self requestGetWithUrlStr:url success:infoData Error:Error];
    }
}

- (void)requestPostWithUrlStr:(NSString *)url paramters:(NSDictionary *)paramter success:(void (^)(NSDictionary *))infoData Error:(void (^)(NSError *))Error {

    [self POST:url parameters:paramter success:^(NSURLSessionDataTask *task, NSDictionary *data) {
        
        if (data) {
            
            infoData(data);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        if (error) {
            
            Error(error);
        }
        
    }];
    
}

- (void)requestGetWithUrlStr:(NSString *)url success:(void (^)(NSDictionary *))infoData Error:(void (^)(NSError *))Error {

    [self GET:url parameters:nil success:^(NSURLSessionDataTask *task, NSDictionary *data) {
        
        if (data) {
            
            infoData(data);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        if (error) {
            
            Error(error);
        }
    }];
    
}
    

@end
